package com.lovetransferjia.chatuidemo.jia.fragment;

import org.json.JSONObject;

import android.R.integer;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.lovetransferjia.chatuidemo.R;
import com.lovetransferjia.chatuidemo.MyApplication;
import com.lovetransferjia.chatuidemo.activity.ChatActivity;
import com.lovetransferjia.chatuidemo.activity.MainView;
import com.lovetransferjia.chatuidemo.jia.fragment.MyInfoFragment.GetInfo;
import com.lovetransferjia.chatuidemo.jia.utility.Communicator;
import com.lovetransferjia.chatuidemo.jia.utility.Utility;
import com.nostra13.universalimageloader.core.ImageLoader;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

public class TodayMatchFragment extends Fragment {
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updatebutton();
		new GetInfo().execute();
	}

	TextView name, bio, school, major, message,active;
	ImageView imageView,bgImageView;
	Button button;
	String nameString = "", genderString = "", hobbyString = "",
			bioString = "", cityString = "", schoolString = "",
			majorString = "", messageString = "";
	String locationString = "";
	ImageLoader imageLoader;
	public int unread = 0;
	public RelativeLayout errorItem;
	public TextView errorText;
	private SmoothProgressBar mPocketBar;
	boolean getinfo=false;
	Communicator communicator;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		imageLoader = MyApplication.imageLoader;
		communicator = (Communicator) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView;
		rootView = inflater.inflate(R.layout.jia_profile, container, false);

		mPocketBar = (SmoothProgressBar) rootView
				.findViewById(R.id.progressBar);
		mPocketBar.setVisibility(View.INVISIBLE);
		errorItem = (RelativeLayout) rootView.findViewById(R.id.rl_error_item);
		errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg);
		name = (TextView) rootView.findViewById(R.id.profile_name);
		//gender = (TextView) rootView.findViewById(R.id.profile_gender);
		// hobby=(TextView) rootView.findViewById(R.id.profile_hobby);
		bio = (TextView) rootView.findViewById(R.id.profile_bio);
		// city=(TextView) rootView.findViewById(R.id.profile_city);
		school = (TextView) rootView.findViewById(R.id.profile_school);
		major = (TextView) rootView.findViewById(R.id.profile_major);
		active=(TextView) rootView.findViewById(R.id.active);
		imageView = (ImageView) rootView.findViewById(R.id.imageView1);
		bgImageView=(ImageView) rootView.findViewById(R.id.imageView2);
		active.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(getActivity() != null)
				Toast.makeText(getActivity(), "活跃度越高，匹配到的Ta也越活跃哦！", Toast.LENGTH_LONG).show();
			}
		});
		
		LayoutParams para;  
		para = bgImageView.getLayoutParams();  
		if(true)
		{
			DisplayMetrics dm = new DisplayMetrics();
			getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
			// 屏幕宽度
			int screenWidth = dm.widthPixels;
			MyApplication.screenWidth=screenWidth;
			// 屏幕高度
			int screenHeight = dm.heightPixels;
			Rect frame = new Rect();  
			getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
			int statusBarHeight = frame.top;
			final float scale = getActivity().getResources().getDisplayMetrics().density;
			para.height =(int) (screenHeight-(98)*scale-statusBarHeight);    
			para.width=screenWidth;
			bgImageView.setLayoutParams(para);
		}
		getinfo=false;
		if(MyApplication.M_name!=null){
			name.setText(MyApplication.M_name);
		}else{ getinfo=true;}
		if(MyApplication.M_school!=null){
			school.setText(MyApplication.M_school);
		}else{ getinfo=true;}
		if(MyApplication.M_major!=null){
			major.setText(MyApplication.M_major);
		}else{ getinfo=true;}
		if(MyApplication.M_bio!=null){
			bio.setText(MyApplication.M_bio);
		}
		if(MyApplication.M_active!=null){
			active.setText(MyApplication.M_active);
		}
		if(MyApplication.M_img!=null){
			imageLoader.displayImage(MyApplication.M_img, imageView);
		}else{ getinfo=true;}
		
			
		
		
		
		
		
		message = (TextView) rootView.findViewById(R.id.profile_message);
		button = (Button) rootView.findViewById(R.id.button);
		if (unread != 0) {
			button.setText(unread + "条未读消息");
		} else {
			button.setText("开始聊天");
		}

		if (MyApplication.match_image != null) {
			imageLoader.displayImage(MyApplication.match_image, imageView);
		}
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				MyApplication.getInstance().getMatch();
				if(MyApplication.match_id!=null && !MyApplication.match_id.equals("0"))
				{
					Intent intent = new Intent(getActivity(), ChatActivity.class);
					intent.putExtra("nickname", nameString);
					intent.putExtra("userId", MyApplication.getInstance().getMatch());
					unread = 0;
					startActivity(intent);
				}else{
					if(getActivity()!=null)
					Toast.makeText(getActivity(), "网速不给力呀，或者一些清理工具把TA清掉了...过会儿再试？或者切走再切回来试试？", Toast.LENGTH_LONG).show();
				}
			}
		});
		
		return rootView;
	}

	public void updatebutton() {
		if (unread != 0) {
			button.setText("开始聊天："+unread + "条未读消息");
			
			
			button.setBackgroundColor(Color.rgb(0xFF, 0x40, 0x40));
		} else {
			button.setText("开始聊天");
			//#63B8FF
			button.setBackgroundColor(Color.rgb(0x63, 0xb8, 0xff));
		}
	}

	public class GetInfo extends AsyncTask<String, Void, Boolean> {
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			mPocketBar.setVisibility(View.INVISIBLE);
			if (result == false) {
				
				//MainView.autologin();
				
				communicator.respond("no one to match");
			}
			if (result == true) {
				name.setText(nameString);
				// city.setText(cityString);
				bio.setText(bioString);
				// hobby.setText(hobbyString);
				school.setText(schoolString);
				major.setText(majorString);
				if (genderString.equals("0"))
					name.append("(女)");
				else {
					name.append("(男)");
				}
				active.setText(activeString);
				imageLoader.displayImage(locationString, imageView);
				MyApplication.match_image = locationString;
				MyApplication.M_img=locationString;
				MyApplication.M_bio=bioString;
				MyApplication.M_major=majorString;
				MyApplication.M_name=name.getText().toString();
				MyApplication.M_school=schoolString;
				MyApplication.M_active=activeString;
				
				new GetUnreadMessageofMatch().execute();
				Log.e("talk first",first);
				if(first.equals("1")){
					 EMMessage msg = EMMessage.createSendMessage(EMMessage.Type.TXT);
				     msg.setReceipt(MyApplication.getInstance().getMatch());
				     TextMessageBody body = new TextMessageBody("你好，很高兴遇到你！");
				     msg.addBody(body);
				     try {
						EMChatManager.getInstance().sendMessage(msg);
					} catch (EaseMobException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if(getinfo==true)
			mPocketBar.setVisibility(View.VISIBLE);
		}

		String failString = "",first="",activeString="";

		@Override
		protected Boolean doInBackground(String... args) {
			String urlString = MyApplication.baseUrl + "match/getmatch.json";
			try {
				JSONObject jsonObject = Utility
						.GETObject(urlString, failString);
				nameString = jsonObject.getString("name");
				genderString = jsonObject.getString("gender");
				cityString = jsonObject.getString("city");
				schoolString = jsonObject.getString("school");
				majorString = jsonObject.getString("major");
				hobbyString = jsonObject.getString("hobby");
				bioString = jsonObject.getString("profile");
				locationString = jsonObject.getString("headimage");
				activeString=jsonObject.getString("active");
				MyApplication.getInstance().setMatch(jsonObject.getString("id"));
				first=jsonObject.getString("first");
				return true;
			} catch (Exception e) {
				Log.w("Getinfo", e.toString());
				failString = "网络连接失败";
			}
			return false;
		}

	}

	public class GetUnreadMessageofMatch extends
			AsyncTask<String, Void, Boolean> {
		

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (unread > 0){
				message.setText("Ta主动搭讪了！");
				updatebutton();
			}
			else {
				message.setText("试试主动搭讪吧！");
			}
		}

		@Override
		protected Boolean doInBackground(String... params) {
			EMConversation conversations = EMChatManager.getInstance()
					.getConversation(MyApplication.getInstance().getMatch());
			unread = conversations.getUnreadMsgCount();
			return null;
		}

	}
}
